package com.dylan.历史.java8.StreamAPI;

import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * Created by Dylan on 2018/7/23.
 */
public class Stream处理3_聚合 {

    public static void main(String[] args) {
        // 聚合操作,简单形式,必须满足 (x op y) op z = x op (y op z)
        Optional<Integer> reduce1 = Stream.of(1, 2, 3, 4, 5, 6).reduce((x, y) -> x + y);
        System.out.println("reduce1:" + reduce1.get());

        /**
         * 聚合操作
         * 标识值: 最初的那个值
         * 累加器: 将结果累加
         * 求和: 当并行计算时,需要该函数在"累加器"的基础上进行求和
         */
        int count = getWords().reduce(0, (total, word) -> total + word.length(), (total1, total2) -> total1 + total2);
        System.out.println("count:" + count);
    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
